package com.douyuehan.doubao.wechatpay.utils;



public class WechatJsapiTicketHolder {

    private static WechatJsapiTicketHolder instance;
    private JsapiTicket jsapiTicket;


    private WechatJsapiTicketHolder() {

    }

    public synchronized static WechatJsapiTicketHolder getInstance() {
        if (instance == null) instance = new WechatJsapiTicketHolder();
        return instance;
    }

    public synchronized JsapiTicket getJsapiTicket() {
        if (jsapiTicket == null || jsapiTicket.expired()) {
            refreshTicket();
        }
        return jsapiTicket;
    }

    public synchronized void refreshTicket() {
        if (jsapiTicket == null || jsapiTicket.expired()) {
            String content = fetchJsapiTicket();
            JsapiTicket jsapiTicket = JsapiTicket.fromJson(content);
            this.jsapiTicket = jsapiTicket;
        }
    }

    public void expireToken() {
        jsapiTicket.setExpiresIn(-30);//强制设置为无效
    }

    protected String fetchJsapiTicket() {
        return WeChatClient.get(WeChatApi.getJsapiTicketUrl(WechatAccessTokenHolder.getInstance().getAccessToken().getAccessToken()));
    }

}
